package com.mall.user.serviceImpl;

import com.mall.user.constant.UserServiceEnum;
import com.mall.user.dto.model.ImageResult;
import com.mall.user.dto.bo.resp.VerifyCode;
import com.mall.user.service.VerifyCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mall.user.utils.VerifyCodeUtils;

import java.io.IOException;
import java.util.UUID;

/**
 * @author: xrj
 * @date: 2022/5/1 1:16
 * @description:
 */
@Slf4j
@Service
@Component
public class VerifyCodeServiceImpl implements VerifyCodeService {

    private final String KAPTCHA_UUID = "kaptcha_uuid";

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public VerifyCode getVerifyCode() {
        VerifyCode verifyCode = new VerifyCode();
        try {
            ImageResult img = VerifyCodeUtils.VerifyCode(140, 43, 4);
            String uuid = UUID.randomUUID().toString();
            RBucket<Object> bucket = redissonClient.getBucket(KAPTCHA_UUID + uuid);
            bucket.set(img.getCode());
            log.info("生成验证码成功,验证码:{},随机uuid:{}", img.getCode(), uuid);
            verifyCode.setImageCode(img.getImg());
            verifyCode.setUuid(uuid);
        } catch (IOException e) {
            log.error("验证码生成失败,过程异常!", e);
        }
        return verifyCode;
    }

    @Override
    public VerifyCode validateVerifyCode(VerifyCode req) {
        RBucket<String> bucket = redissonClient.getBucket(KAPTCHA_UUID + req.getUuid());
        VerifyCode resp = new VerifyCode();
        if (bucket == null){
            resp.setCode(UserServiceEnum.VERIFY_ERROR.getCode());
            resp.setMsg(UserServiceEnum.VERIFY_ERROR.getMsg());
        }else {
            String validateCode = bucket.get();
            String code = req.getImageCode();
            log.info("用户输入验证码:{},uuid:{},从redis中取出验证码:{}", code, req.getUuid(), validateCode);
            if (StringUtils.isNotBlank(validateCode) && code.equalsIgnoreCase(validateCode)) {
                resp.setCode(UserServiceEnum.SUCCESS.getCode());
                resp.setMsg(UserServiceEnum.SUCCESS.getMsg());
            } else {
                resp.setCode(UserServiceEnum.VERIFY_ERROR.getCode());
                resp.setMsg(UserServiceEnum.VERIFY_ERROR.getMsg());
            }
        }
        return resp;
    }
}
